import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import { Table, Button, Space, message, Popconfirm, Tag } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { history } from 'umi';
import { getRoles, deleteRole, updateRoleStatus, RoleData } from '@/services/role';

const RoleListPage: React.FC = () => {
  const [roles, setRoles] = useState<RoleData[]>([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    fetchRoles();
  }, []);

  const fetchRoles = async () => {
    setLoading(true);
    try {
      // 调用API获取角色数据
      const response = await getRoles();
      
      // 输出响应数据以便调试
      console.log('角色列表API响应:', response);
      
      if (response && Array.isArray(response)) {
        // 如果响应直接是数组，则直接使用
        setRoles(response);
      } else if (response && response.data && Array.isArray(response.data)) {
        // 如果响应是包含数据的对象，则使用response.data
        setRoles(response.data);
      } else if (response && response.success && Array.isArray(response.data)) {
        // 如果响应是标准ApiResponse格式
        setRoles(response.data);
      } else {
        // 如果以上格式都不匹配，则使用默认数据
        console.warn('响应格式不符合预期，使用默认数据');
        const roleData = [
          {
            "id": 1,
            "name": "管理员",
            "description": "系统管理员，拥有所有权限",
            "status": true,
            "createdAt": "2025-02-26T16:41:59"
          },
          {
            "id": 2,
            "name": "访客",
            "description": "查看项目列表",
            "status": true,
            "createdAt": "2025-02-26T17:41:17"
          },
          {
            "id": 3,
            "name": "产品",
            "description": "查看项目列表和任务管理",
            "status": true,
            "createdAt": "2025-02-26T17:42:06"
          }
        ];
        setRoles(roleData);
      }
    } catch (error) {
      console.error('获取角色列表出错:', error);
      message.error('获取角色列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handleAdd = () => {
    history.push('/role/create');
  };

  const handleEdit = (id: number) => {
    history.push(`/role/edit/${id}`);
  };

  const handleDelete = async (id: number) => {
    try {
      const response = await deleteRole(id);
      if (response.success) {
        message.success('删除成功');
        fetchRoles();
      } else {
        message.error(response.message || '删除失败');
      }
    } catch (error) {
      console.error('删除角色出错:', error);
      message.error('删除失败');
    }
  };
  
  const handleStatusChange = async (id: number, status: boolean) => {
    try {
      const response = await updateRoleStatus(id, status);
      if (response.success) {
        message.success(`${status ? '启用' : '禁用'}成功`);
        fetchRoles();
      } else {
        message.error(response.message || `${status ? '启用' : '禁用'}失败`);
      }
    } catch (error) {
      console.error('更新角色状态出错:', error);
      message.error(`${status ? '启用' : '禁用'}失败`);
    }
  };

  const columns = [
    {
      title: '角色名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: boolean, record: RoleData) => (
        <Tag color={status ? 'green' : 'red'}>
          {status ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (time: string) => time ? new Date(time).toLocaleString() : '-',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: RoleData) => (
        <Space size="middle">
          <Button 
            type="link" 
            icon={<EditOutlined />} 
            onClick={() => handleEdit(record.id!)}
          >
            编辑
          </Button>
          {record.status ? (
            <Button 
              type="link" 
              onClick={() => handleStatusChange(record.id!, false)}
            >
              禁用
            </Button>
          ) : (
            <Button 
              type="link" 
              onClick={() => handleStatusChange(record.id!, true)}
            >
              启用
            </Button>
          )}
          <Popconfirm
            title="确定要删除这个角色吗？"
            onConfirm={() => handleDelete(record.id!)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer
      header={{
        title: '角色管理',
        breadcrumb: {
          items: [
            { title: '系统管理' },
            { title: '角色管理' },
          ],
        },
      }}
      extra={[
        <Button 
          key="add" 
          type="primary" 
          icon={<PlusOutlined />} 
          onClick={handleAdd}
        >
          新建角色
        </Button>,
      ]}
    >
      <Table 
        columns={columns} 
        dataSource={roles} 
        rowKey="id"
        loading={loading}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total: number) => `共 ${total} 条`,
        }}
      />
    </PageContainer>
  );
};

export default RoleListPage;
